<template>
	<div class="mainYuliang" >
		<div class="twoStageWindow" style="overflow:hidden">
			<div class="twoStageWindowTitle">
				<span style="position: absolute;left: 10px;">
					<!-- {{status=="edit"?"入库登记":(status=="rukutijiao"?"入库修改":"查看详情")}} -->
          余量{{isEdit == 'edit'?"修改":"详情"}}

				</span>
				<div class="twoStageWindowClose">
					<el-button size="mini" type="primary" v-on:click="doSbumit(1)"v-if="isEdit != 'look'" :disabled="!isRepeat">提交</el-button>
					<el-button size="mini" v-on:click="close">关闭</el-button>
				</div>
			</div>
			<div class="containercontent" style="margin-top:40px;height:calc(100% - 40px);padding-top: 0;">
				<el-form label-width="110px" :inline="false" class="demo-form-inline kucunForm" :model="yuliangForm" :rules="rules" ref="rukuForm">
					<el-form-item label="物资编号" prop='number' >
						<el-col :span="22">
							<el-input size="mini"  disabled v-model="yuliangForm.number"></el-input>
						</el-col>
					</el-form-item>
          <!-- materialName -->
          <el-form-item label="名称" prop='materialName' >
          	<el-col :span="22">
          		<el-input size="mini"  disabled v-model="yuliangForm.materialName"></el-input>
          	</el-col>
          </el-form-item>
          <el-form-item label="批号" prop='batch' >
						<el-col :span="22">
							<el-input size="mini"  disabled v-model="yuliangForm.batch"></el-input>
						</el-col>
					</el-form-item>
          <el-form-item label="余量" prop='qty' >
          	<el-col :span="22">
          		<el-input size="mini"  disabled v-model="yuliangForm.qty"></el-input>
          	</el-col>
          </el-form-item>

          <el-form-item label="浓度" prop='concentration' >
          	<el-col :span="22">
          		<el-input size="mini"  :disabled = "isEdit == 'look'" v-model="yuliangForm.concentration"></el-input>
          	</el-col>
          </el-form-item>
          <el-form-item label="纯度" prop='purity' >
          	<el-col :span="22">
          		<el-input size="mini"  :disabled = "isEdit == 'look'" v-model="yuliangForm.purity"></el-input>
          	</el-col>
          </el-form-item>
          <el-form-item label="介质" prop='medium' >
          	<el-col :span="22">
          		<el-input size="mini"  :disabled = "isEdit == 'look'" v-model="yuliangForm.medium"></el-input>
          	</el-col>
          </el-form-item>
          <el-form-item label="包装规格" prop='spce' >
          	<el-col :span="22">
          		<el-input size="mini" v-model="yuliangForm.spce" :disabled = "isEdit == 'look'" ></el-input>
          	</el-col>
          </el-form-item>
          <el-form-item label="生产商" prop='companyCode' >
          	<el-col :span="22">
          		<el-select :disabled = "isEdit == 'look'" style="width: 100%;" v-model="yuliangForm.companyCode" size="mini" filterable clearable>
          			<!--被删除或者停用的不可选中-->
          			<el-option v-for="item in supplierData" :key="item.id" :label="item.name" :value="item.id" :disabled = "isEdit == 'look'">
          			</el-option>
          		</el-select>
          	</el-col>
          </el-form-item>
          <el-form-item label="存储位置" prop='stockCode' >
          	<el-col :span="22">
          		<el-autocomplete class="inline-input" size="mini" v-model="yuliangForm.stockCode" style="width: 100%;" :title = "yuliangForm.stockCode" :fetch-suggestions="querySearch2" :disabled = "isEdit == 'look'">
          		</el-autocomplete>
          	</el-col>
          </el-form-item>
          <el-form-item label="有效期" prop='validitydate' >
          	<el-col :span="22">
          		<!-- <el-input size="mini" :disabled = "isEdit == 'look'"  v-model="yuliangForm.validitydate"></el-input> -->
              <el-date-picker  :disabled = "isEdit == 'look'" size="mini" v-model="yuliangForm.validitydate" type="date"  placeholder="选择日期"
              value-format="yyyy-MM-dd" style="width: 100%;"> </el-date-picker>
          	</el-col>
          </el-form-item>

				</el-form>
				<div class="elTab">
					<el-tabs v-model="activeName">
						<el-tab-pane label="标样详情" name="first"  v-if = "yuliangForm.standardSample == 1 && $parent.userOpernation.systemQuery.display">
              <el-button v-if="isEdit == 'edit'" style="float: right;margin-bottom: 10px;" type="primary" size="mini" @click="addOne">添加</el-button>
							 <el-table :data="yuliangForm.itemStandardList" style="width: 100%;height:calc(100% - 50px);" class="tableCon" size="mini">
							   <el-table-column label="序号" min-width="50px" fixed>
							     <template slot-scope="scope">
							       {{scope.$index+1}}
							     </template>
							   </el-table-column>

							   <el-table-column property="itemCode" label="检测项目" fixed min-width="120px">
							     <template slot-scope="scope">
							       <el-select v-model="scope.row.itemCode" filterable placeholder="选择检测项目" size="mini" style="width:100%;" :disabled="isEdit == 'look'" @change = "(val) =>getDetecAndUnit(val,scope.row)">
							         <el-option v-for="item in projectData" :key="item.code" :label="item.name" :value="item.code">
							         </el-option>
							       </el-select>
							     </template>
							   </el-table-column>
							  <!-- <el-table-column property="detectability" label="能力参数" fixed min-width="180px">
							     <template slot-scope="scope">
							        <el-select v-model="scope.row.detectabilityName" filterable placeholder="选择能力参数" v-if = "isEdit !='look'"  size="mini" style="width:100%;" value-key = "detectability" :disabled="isEdit == 'look'"  @focus="getDetecAndUnit1(scope.row.itemCode,scope.row)" @change = "(val) => getUnit(val,scope.row)">
							        <el-option v-for="item in scope.row.detectList" :key="item.detectability" :label="item.detectabilityName" :value="item">
							         </el-option>
							       </el-select>
							       <el-select v-model="scope.row.detectabilityName" filterable placeholder="选择能力参数" v-if = "isEdit =='look'" :title = "scope.row.detectabilityName" size="mini" style="width:100%;"
                     value-key = "detectability" :disabled="isEdit == 'look'"  @focus="getDetecAndUnit1(scope.row.itemCode,scope.row)" @change = "(val) => getUnit(val,scope.row)">

							         <el-option v-for="item in scope.row.detectList" :key="item.detectability" :label="item.detectabilityName" :value="item">
							         </el-option>
							       </el-select>
							     </template>
							   </el-table-column> -->
							   <el-table-column property="unit" label="单位" min-width="80px">
                  <template slot-scope="scope">
                     <el-select v-model="scope.row.unit" filterable placeholder="选择单位" v-if = "isEdit !='look'"  size="mini" style="width:100%;" :disabled="isEdit == 'look'">
                     <el-option v-for="item in unitList" :key="item.code" :label="item.ename" :value="item.code">
                      </el-option>
                    </el-select>
                    <el-select v-model="scope.row.unit" filterable placeholder="选择单位" v-if = "isEdit =='look'" :title = "scope.row.detectabilityName" size="mini" style="width:100%;"
                   :disabled="isEdit == 'look'"  >

                      <el-option v-for="item in unitList" :key="item.code" :label="item.ename" :value="item.code">
                      </el-option>
                    </el-select>
                  </template>
							   </el-table-column>
							   <el-table-column property="nogndu" label="浓度" min-width="100px">
							     <template slot-scope="scope">
							       <el-input :disabled="isEdit == 'look'" v-model="scope.row.concentration" size="mini" placeholder="请输入内容"></el-input>
							     </template>
							   </el-table-column>
							   <el-table-column property="dixian" label="低限" min-width="80px">
							     <template slot-scope="scope">
							       <el-input :disabled="isEdit == 'look'"  oninput="this.value=this.value.replace(/[^0-9.]+/,'');" v-model="scope.row.lowLimit"
							         size="mini" placeholder="请输入内容"></el-input>
							     </template>
							   </el-table-column>
							   <el-table-column property="gaoxian" label="高限" min-width="80px">
							     <template slot-scope="scope">
							       <el-input :disabled="isEdit == 'look'"  v-model="scope.row.highLimit" oninput="this.value=this.value.replace(/[^0-9.]+/,'');"
							         size="mini" placeholder="请输入内容"></el-input>
							     </template>
							   </el-table-column>
							   <el-table-column label="操作" min-width="100px" v-if = "isEdit != 'look'">
							     <template slot-scope="scope">
							       <el-button type="text" size="mini" :disabled = "scope.row.id != undefined && scope.row.id != null && scope.row.id != ''"
                      @click="deleteOne(scope.row,scope.$index)">删除</el-button>
							     </template>
							   </el-table-column>
							 </el-table>
						</el-tab-pane>
            <el-tab-pane label="附件" name="third">
                <div style="margin-bottom: 10px;overflow: hidden;">
                  <input type="file" name="file" id="plFile" @change="upload" style="visibility: hidden;width: 0;height: 0;" multiple>
                  <el-button size="mini" type="primary" style="float:right" @click="uploadClick" v-if="isEdit == 'edit' && $parent.userOpernation.systemQuery.display">上传附件</el-button>
                </div>
                <el-table :data="renwufujian" style="width: 100%;height:calc(100% - 40px)" class="tableCon" size="mini" highlight-current-row cell-class-name="batchtablecell"
                key="renwufujian" >
                  <el-table-column label="序号" width="49px" fixed>
                    <template slot-scope="scopea">
                      {{scopea.$index+1}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="fileName" label="名称" min-width="90px">
                  </el-table-column>
                  <el-table-column label="上传人" prop="createByName" min-width="90px">
                  </el-table-column>
                  <el-table-column label="操作" min-width="90px">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click="deleteattachment(scope.row,scope.$index)" v-if="isEdit == 'edit' && $parent.userOpernation.systemQuery.display">删除</el-button>
                      <el-button type="text" size="small" @click="dlownloadattachment(scope.row)">下载</el-button>
                    </template>
                  </el-table-column>
                </el-table>

            </el-tab-pane>
          </el-tabs>
				</div>
			</div>
		</div>

	</div>
</template>

<script>
import { mapState } from 'vuex'
import $ from  'jquery'
export default {
	data() {
		return {
			pickerOptions: {
				disabledDate(time) {
					return time.getTime() > Date.now();
				},
			},
			saveType: '',
			qualitySampleAddShow: false,
			bjorck: '',
			xuanzewuziShow: false,
			options: [],
			selectRow: [],
			samplesetObj: {},
			stockComList: [],
			isRepeat: true,
			rules: {
				// materialName: [
				// 	{ required: true, trigger: 'change', message: "请选择登记人" },
				// ],

			},
			instockdetList: [], //选择物资浓度和纯度的列表
			pickerOptions1: { // 只能选择今天之前
				disabledDate(time) {
					return time.getTime() < Date.now() - 8.64e7 ;//如果没有后面的-8.64e6就是不可以选择今天的
				}
			},

      projectData:[],
      supplierData:[],
      unitList:[],
      activeName:'first',
      renwufujian:[],
		}
	},
	props: ['avisible','isEdit','yuliangForm'],
	components: {

	},
	computed: {
		...mapState(['enableStatus', 'typeofAbilityTableDate', 'materialType', 'EmployeeByLabs']),
		TableHeight() {
			return ((window.innerHeight - 180) - 240)
		},
	},
	created() {

	},
	mounted() {
    if(this.yuliangForm.standardSample == 1 && this.$parent.userOpernation.select.display){
      this.activeName = 'first'
    }else{
      this.activeName = 'third'
    }
    $(".mainYuliang .twoStageWindow").height($(".contain.smallCon").height() - 40)
    $(".mainYuliang .twoStageWindow").width($(".contain.smallCon").width())
    $(".mainYuliang .twoStageWindow").css({"position":"fixed","left":"190px","top":"76px"})
    // console.log(this.yuliangForm)
    // this.yuliangForm.itemStandardList.forEach((item) =>{
    //   console.log(item)
    //   var obj = {
    //     detectabilityName:item.detectabilityName,
    //     detectability:item.detectability
    //   }
    //   this.$set(item,'detectabilityName',obj)
    // })
    this.readItemSet();
    this.readSupplier()
    this.readLabUnitList()
	},
	watch: {
    activeName(val){
      if(val == 'third'){
        this.getFilePathByIds();
      }
    }
	},
	methods: {
    readItemSet() {
      var params = null;
      this.$http({
        method: 'post',
        apiUrl: '/technology/readItemBeanList.htm',
        params: params,
        isJson: false,
      }).then(res => {
        if (res.code === 0) {
          this.projectData = res.data

        }
      }, )
    },
    // 获取生产商
    readSupplier(){
      this.$http({
      	apiUrl: 'resource/readSupplierComboList.htm',
      	method: 'post',
      	params: '',
      	isJson: false
      }).then(res=>{
      	if(res.code == 0) {
      		this.supplierData = res.data
      	}
      })
    },
   // 仓库
   querySearch2(queryString, cb ) {
   	this.readStockComList().then(res => {
   		for (var i in res.data) {
   			res.data[i].value = res.data[i].name
   		}
   		var restaurants = res.data;
   		var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
   		// 调用 callback 返回建议列表的数据
   		cb(results);
   	})
   },
   createFilter(queryString) {
   	return (restaurant) => {
   		return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
   	};
   },
   readStockComList() {
   	return new Promise((resolve, reject) => {
   		this.$http({
   			apiUrl: '/system/readStockComList.htm',
   			method: 'post',
   		}).then(res => {
   			if (res.code === 0) {
   				resolve(res)
   			}
   		})
   	})
   },

    addOne() {
      this.yuliangForm.itemStandardList.push({
        itemCode: "",
        itemName: "",
        concentration: "",
        lowLimit: "",
        highLimit: "",
        detectability:"",
        unitName:"",
        unit:"",
        detectList:[],
      })
    },
    deleteOne(row,index){
      this.yuliangForm.itemStandardList.splice(index,1)
    },
    doSbumit(){

      this.$refs['rukuForm'].validate((valid) => {
      	if (valid) {

			for(var i in this.yuliangForm.itemStandardList){
        if(this.yuliangForm.itemStandardList[i].unit == "" ){
            this.$notify({
              message: '单位不能为空',
              type: 'info',
              title: "警告"
            });
            return;
        }
				// if(this.yuliangForm.itemStandardList[i].detectabilityName == undefined){
				//   this.yuliangForm.itemStandardList[i].detectabilityName = ""
				// }

				// if(this.yuliangForm.itemStandardList[i].detectabilityName.detectability != undefined){
				//    this.yuliangForm.itemStandardList[i].detectability = this.yuliangForm.itemStandardList[i].detectabilityName.detectability
				//    this.yuliangForm.itemStandardList[i].detectabilityName = this.yuliangForm.itemStandardList[i].detectabilityName.detectabilityName

				// }else{
				//   this.yuliangForm.itemStandardList[i].detectability = this.yuliangForm.itemStandardList[i].detectability
				//   this.yuliangForm.itemStandardList[i].detectabilityName = this.yuliangForm.itemStandardList[i].detectabilityName
				// }
				// if(JSON.stringify(this.yuliangForm.itemStandardList[i].detectabilityName) == "{}"){
				//   this.yuliangForm.itemStandardList[i].detectabilityName = '';
				// }
        if(this.yuliangForm.itemStandardList[i].itemCode){
          this.projectData.forEach((item) =>{
            if(item.code == this.yuliangForm.itemStandardList[i].itemCode){
              this.yuliangForm.itemStandardList[i].itemName = item.name;
            }
          })
        }
        if(this.yuliangForm.itemStandardList[i].unit){
          this.unitList.forEach((item) =>{
            if(item.code == this.yuliangForm.itemStandardList[i].unit){
              this.yuliangForm.itemStandardList[i].unitName = item.ename;
            }
          })
        }
			}
          this.isRepeat = false;
          this.$http({
          	apiUrl: "resource/updateMateStock.htm",
          	method: 'post',
          	params: this.yuliangForm
          }).then(res => {
          	this.isRepeat = true;
          	if (res.code === 0) {
          			this.$notify({
          				showClose: true,
          				message: '提交成功！',
          				type: 'success',
          				title: "成功"
          			})
                this.close();
                this.$parent.readStockByMatarialCode(this.yuliangForm.materialCode).then(res => {
                	this.$parent.subTable = res.data;
                })
              }
            })
        }
      })
    },


		//			2、(1)交互名称：入库登记
		doSbumit1(code) {
      console.log(this.yuliangForm)
			this.$refs['rukuForm'].validate((valid) => {
				if (valid) {
					let url;

					if (this.yuliangForm.instockdetBeanList.length == 0) {
						this.$notify({
							showClose: true,
							message: '请添加入库物资',
							type: 'warning',
							title:"警告"
						})
						return
					}
					let set1 = new Set() //判断是否有重复批号和编号的
					for(var i in this.yuliangForm.instockdetBeanList){
						var numberBatch = this.yuliangForm.instockdetBeanList[i].number + this.yuliangForm.instockdetBeanList[i].batch;
						set1.add(numberBatch)
					}
					if(set1.size !== this.yuliangForm.instockdetBeanList.length){
						this.$notify({
							showClose: true,
							message: '物资批号与物资编号不能同时相同!',
							type: 'warning',
							title:"警告"
						})
						return;
					}

					if (this.saveType == 'rukudengji') {
						url = 'resource/addInstock.htm'
						for (let item of this.yuliangForm.instockdetBeanList) {
							if (!item.hasOwnProperty('itemStandardList')) {
								item.itemStandardList = []
							}
						}
					} else if (this.saveType == 'rukutijiao') {
						url = 'resource/updateInstock.htm'
					}

					this.isRepeat = false;
					this.$http({
						apiUrl: url,
						method: 'post',
						params: this.yuliangForm
					}).then(res => {
						this.isRepeat = true;
						if (res.code === 0) {
							if (code == 0) {
								this.$notify({
									showClose: true,
									message: '保存成功！',
									type: 'success',
									title: "成功"

								})
								this.yuliangForm.id = res.data; //如果是保存的话 把返回的id重新赋值给这条数据
								this.saveType = 'rukutijiao'

							} else {
								this.$notify({
									showClose: true,
									message: '提交成功！',
									type: 'success',
									title: "成功"
								})
								this.close()

							}
							this.$parent.readInstockList()

						}
					})
				} else {

				}
			})

		},
		//			5、(1)交互名称：修改入库登记
		updateInstock(code) {

		},
    // 选中检测项目后，获取能力参数和单位列表

    getDetecAndUnit(val,row){
      // row.detectability = "";
      // row.detectabilityName = {};
      // row.unit = "";
      // row.unitName = "";
     // this.getDetecAndUnit1(val,row);
    },
    // technology/readLabUnitList.htm
    readLabUnitList(val,row){
      this.$http({
        method: 'post',
        apiUrl: '/technology/readLabUnitList.htm',
        // params: {itemCode:val},
        // isJson: false,
      }).then(res => {
        if (res.code === 0) {
          this.unitList = res.data
          // this.$set(row,'detectList',res.data)

        }
      })
    },
    getDetecAndUnit1(val,row){
      this.$http({
        method: 'post',
        apiUrl: '/resource/getDetecAndItemUnitList.htm',
        params: {itemCode:val},
        isJson: false,
      }).then(res => {
        if (res.code === 0) {
          this.$set(row,'detectList',res.data)

        }
      })
    },
    getUnit(val,row){

      row.unit = row.detectabilityName.unit;
      row.unitName = row.detectabilityName.unitName;

    },


		close() {
			this.$parent.editYuliangShow = false
			this.isRepeat = true;
		},

		//	3、(1)交互名称：获取标样设置列表
		readSampleSet(row) {
			this.$http({
				apiUrl: 'resource/readSampleSet.htm',
				method: 'post',
				params: {
					number: row.number,
					batch: row.batch
				},
				isJson: false
			}).then(res => {
				if (res.code === 0) {
					if (this.selectRow.itemStandardList.length == 0) {
						for (var i in res.data) {
							this.selectRow.itemStandardList.push(res.data[i])
						}
					}

					this.qualitySampleAddShow = true;
				}
			})
		},
    getFilePathByIds() {
      console.log(this.yuliangForm)
       this.$http({
         method: 'post',
         apiUrl: '/download/getFilePathByIds.htm',
         params: { ids: this.yuliangForm.number+this.yuliangForm.batch },
         isJson: false,
       }).then(res => {
         if (res.code == 0) {
           this.renwufujian = res.data
         }

       })
     },
     uploadClick() {
       document.getElementById('plFile').click()
     },
     upload(event) {
       var files = document.getElementById('plFile').files[0];

       var formData = new FormData();
       // for(var i of files){
         formData.append('file', files)
       // }
       formData.append('type', 3) //3是附件的意思
       formData.append('taskType', null)
       formData.append('detectability', null)
       formData.append('fileType', 'inStock')
       formData.append('ids',this.yuliangForm.number+this.yuliangForm.batch)
       this.$axios({
         method: 'post',
         url: '/download/fileUpload.htm',
         data: formData,
         headers: {
           'Content-Type': 'multipart/form-data',
           'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
          }
       }).then((res) =>{
         var data = res.data
           event.target.value= "";
          if (data.code == 0) {
            this.$notify({
              title: '消息',
              message: '上传成功',
              type: 'success'
            })
            this.getFilePathByIds();
          } else {
            this.$notify({
             					title: '消息',
             					message: '上传失败',
             					type: "warning"
             			})
          }
       }).catch(() =>{

       })


     },
     deleteattachment(row,index){
       this.$confirm('是否删除', '提示', {
       	confirmButtonText: '确定',
       	cancelButtonText: '取消',
       	type: 'warning'
       }).then(() => {
         if(row.id){
           this.$http({
           	method: 'post',
           	apiUrl: '/download/fileDelete.htm',
           	params: {
           		id: row.id,
           	},
           	isJson: false,
           }).then(res => {
           	if (res.code === 0) {
           		this.$message({
           			type: 'success',
           			message: '删除成功!'
           		});
              this.getFilePathByIds();
           	}
           })
         }
         

       }).catch(() => {
       	this.$message({
       		type: 'info',
       		message: '已取消删除'
       	});
       });

     },
    // 下载附件
    dlownloadattachment(row) {
    	var url = "/download/fileDownload.htm"
       let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
    	window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
    },
	}
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
	-webkit-appearance: none;
}

input[type="number"] {
	-moz-appearance: textfield;
}

.containercontent .width73 {
	width: 73px;
}

.kucunForm .el-form-item {
	width: 32%;
	display: inline-block;
	margin-bottom: 15px;
}



.kucunForm {
		height: 225px;
	}

.mainYuliang .elTab {
	padding: 0 20px;
	height:calc(100% - 230px)
}

.mainYuliang .elTab .el-tabs {
	height: 100%;
}

.mainYuliang .remark .el-form-item__content {
	width: calc(100% - 80px);
}
.mainYuliang .el-tabs__content .el-tab-pane{
		height:100%;
	}
.mainYuliang .el-autocomplete-suggestion li {
	padding: 0 5px !important;
}
</style>
